package com.lhy.admin.common.secure.exception;

import com.lhy.admin.common.mvcplus.entity.RespResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * @author hyluan
 * @ClassName: ExceptionHandler
 * @Description: 全局异常处理类
 * @date 2017年7月20日 上午11:48:45
 * @Copyright: Copyright (c) 2017 wisedu
 */
@ControllerAdvice
@Slf4j
public class ExceptionHandler {

    /**
     * @param e
     * @param response
     * @return
     * @Title: exceptionHandler
     * @Description:token异常处理
     */
    @org.springframework.web.bind.annotation.ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public RespResult<Object> exceptionHandler(RuntimeException e,
                                               HttpServletResponse response) {
        log.error("exceptionHandler", e);
        if (e instanceof UnAuthorizedException) {
            log.error("未授权");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return RespResult.fail().setMsg(e.getMessage()).setData(HttpServletResponse.SC_FORBIDDEN);
        } else if (e instanceof UnAuthenticatiedException) {
            log.error("session已失效或未登录");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return RespResult.fail().setMsg(e.getMessage()).setData(HttpServletResponse.SC_UNAUTHORIZED);
        }
        response.setStatus(HttpServletResponse.SC_OK);
        return RespResult.fail().setMsg(e.getMessage());
    }


}
